package com.rdc.jiajiadictionary.data.getnotebook;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;


import com.rdc.jiajiadictionary.bean.Word;
import com.rdc.jiajiadictionary.database.DataBaseHelper;

import java.util.ArrayList;
import java.util.List;

public class NotebookModel implements com.rdc.jiajiadictionary.data.getnotebook.NotebookModelInterface {
    private Context context;
    public NotebookModel(Context context){
        this.context = context;
    }

    /**
     * 从数据库中获取生词本的list
     * @param sort
     * @return
     */
    @Override
    public List<Word> getNotebookWordFromDatabase(String sort) {
        List<Word> words = new ArrayList<Word>();
        DataBaseHelper dataBaseHelper = new DataBaseHelper(context,"word.db",null,1);
        SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
        Cursor cursor = db.query("notebook",null,null,null,null,null,"word_name "+sort);

//        排序操作：就是填充最后一个字段**
//        填充规则就“ 列名   desc”，其中desc表示降序排列，asc是升序排列
//        如“name desc”就是对name的数据进行升序排列
        if(cursor.moveToFirst()){
            do {
                Word word = new Word();
                word.setWord_name(cursor.getString(cursor.getColumnIndexOrThrow("word_name")));
                word.setPart(cursor.getString(cursor.getColumnIndexOrThrow("word_parts")));
                word.setExchange(cursor.getString(cursor.getColumnIndexOrThrow("word_exchange")));
                word.setPh_am(cursor.getString(cursor.getColumnIndexOrThrow("word_ph_am")));
                word.setPh_en(cursor.getString(cursor.getColumnIndexOrThrow("word_ph_en")));
                word.setPh_am_mp3(cursor.getString(cursor.getColumnIndexOrThrow("word_ph_am_mp3")));
                word.setPh_en_mp3(cursor.getString(cursor.getColumnIndexOrThrow("word_ph_en_mp3")));
                word.setDownloadPath(cursor.getString(cursor.getColumnIndexOrThrow("word_download")));
                words.add(word);
            }while (cursor.moveToNext());
        }
        cursor.close();
        db.close();
        return words;
    }

    /**
     * 删除生词本中的全部单词
     */
    @Override
    public void deleteAllNotebookInDatabase() {
        DataBaseHelper dataBaseHelper = new DataBaseHelper(context,"word.db",null,1);
        SQLiteDatabase database = dataBaseHelper.getWritableDatabase();
        database.delete("notebook",null,null);
        database.close();
    }

    @Override
    public void deleteWordFromNotebookInDatabase(String wordName) {
        DataBaseHelper dataBaseHelper = new DataBaseHelper(context,"word.db",null,1);
        SQLiteDatabase database = dataBaseHelper.getWritableDatabase();
        database.delete("notebook","word_name = ?",new String[]{wordName});
        database.close();
    }
}
